<template>
  <div class="payment-container">
    <el-card class="payment-card">
      <!-- 顶部标题 -->
      <div class="header">
        <h1>订单支付</h1>
        <el-steps :active="1" align-center>
          <el-step title="填写信息" />
          <el-step title="支付订单" />
          <el-step title="预订成功" />
        </el-steps>
      </div>

      <!-- 订单信息展示 -->
      <el-card shadow="never" class="order-info">
        <h2>订单信息</h2>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="酒店名称">{{ orderInfo.hotelName }}</el-descriptions-item>
          <el-descriptions-item label="房型">
            <div v-for="(room, index) in orderInfo.selectedRooms" :key="index" style="margin-bottom: 4px;">
              {{ room.name }} × {{ room.bookingNum }}间 (¥{{ room.basePrice }}/间)
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="入住日期">{{ formatDate(orderInfo.checkIn) }}</el-descriptions-item>
          <el-descriptions-item label="离店日期">{{ formatDate(orderInfo.checkOut) }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span class="price">¥{{ orderInfo.totalPrice }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单编号">{{ bookingResult.orderId || '待生成' }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 备注信息 -->
      <el-card shadow="never" class="remarks-section">
        <h2>备注信息</h2>
        <el-input v-model="remarks" type="textarea" :rows="3" placeholder="请输入您的特殊要求（如无烟房、高楼层等）" maxlength="200"
          show-word-limit />
      </el-card>

      <!-- 支付按钮 -->
      <div class="payment-actions">
        <el-button type="primary" size="large" @click="handlePayment" :loading="loading">
          立即支付 ¥{{ orderInfo.totalPrice }}
        </el-button>
        <el-button size="large" @click="goBack">返回修改</el-button>
      </div>
    </el-card>

    <!-- 支付成功对话框 -->
    <el-dialog title="支付成功" v-model="paymentSuccess" width="30%" center :show-close="false"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="success-content">
        <el-icon color="#67C23A" :size="60">
          <CircleCheckFilled />
        </el-icon>
        <p>支付成功！订单已确认</p>
        <p>订单编号：{{ bookingResult.value?.data?.orderId || bookingResult.value?.orderId || '待生成' }}</p>
        <p>总金额：¥{{ bookingResult.value?.data?.totalAmount || 0 }}</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="goToOrderDetail">查看订单详情</el-button>
        <el-button @click="goToHome">返回首页</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { CircleCheckFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 订单信息
const orderInfo = computed(() => {
  return {
    hotelId: route.query.hotelId,
    hotelName: route.query.hotelName,
    checkIn: route.query.checkIn,
    checkOut: route.query.checkOut,
    adult: Number(route.query.adult || 1),
    children: Number(route.query.children || 0),
    totalPrice: Number(route.query.totalPrice || 0),
    totalNum: Number(route.query.totalNum || 0),
    selectedRooms: JSON.parse((route.query.selectedRooms as string) || '[]')
  }
})

// 备注信息
const remarks = ref('')
const loading = ref(false)
const paymentSuccess = ref(false)
const bookingResult = ref<{
  data?: {
    orderId?: string
    totalAmount?: number
  }
  orderId?: string
  message?: string
}>({})

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

const formatBackendDate = (dateObj) => {
  const date = new Date(dateObj)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}
// 处理支付
const response = ref<{ orderId?: string }>({})
const handlePayment = async () => {
  try {
    loading.value = true

    // 准备预订数据
    const bookingData = {
      userId: 1, // 实际应用中从用户登录信息获取
      hotelId: orderInfo.value.hotelId,
      checkInDate: orderInfo.value.checkIn,
      checkOutDate: orderInfo.value.checkOut,
      specialRequests: remarks.value,
      totalAmount: orderInfo.value.totalPrice,
      roomBookingsDetail: orderInfo.value.selectedRooms.map(room => ({
        roomTypeId: room.id,
      }))
    }
    console.log(bookingData)
    // 调用后端API
    const response = await axios.post('http://localhost:8080/bookings', bookingData)
    bookingResult.value = response.data
    console.log('预订结果:', response.data)
    console.log('完整响应:', JSON.stringify(response.data.orderId, null, 2));
// 检查实际数据结构
// 可能是 response.data.data.orderId 或其他嵌套路径
    // 显示支付成功
    paymentSuccess.value = true
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 返回修改
const goBack = () => {
  router.go(-1)
}

// 查看订单详情
const goToOrderDetail = () => {
  paymentSuccess.value = false;
  
  // 验证orderId是否存在
  if (!bookingResult.value?.orderId) {
    ElMessage.error('订单ID获取失败,请稍后重试');
    return;
  }

  // 使用命名路由更安全
  router.push({
    name: 'order-detail',  // 必须与路由配置中的name一致
    params: { 
      orderId: bookingResult.value?.data?.orderId
                 }
  }).catch(err => {
    console.error('路由跳转失败:', err);
    router.push('/'); // 失败时跳转到首页
  });
}
// 返回首页
const goToHome = () => {
  paymentSuccess.value = false
  router.push('/')
}
</script>

<style scoped>
/* 样式保持不变 */
</style>